<template>
  <div class="container">
    <van-nav-bar
      :title="`购物车(${totalNum})`"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <div class="list-container">
      <van-pull-refresh v-model="isLoading" @refresh="refresh">
        <van-empty description="购物车无内容" v-if="cartList?.length === 0">
          <van-button
            round
            type="danger"
            @click="$router.push('/')"
            class="bottom-button"
          >
            立即购物
          </van-button>
        </van-empty>
        <van-swipe-cell v-for="item in cartList" :key="item.proid">
          <div class="cell-left">
            <van-checkbox
              @click="handleSelectOne(item.cartid, item.flag)"
              v-model="item.flag"
            ></van-checkbox>
            <van-card
              tag="标签"
              :num="item.num"
              :price="item.originprice"
              :title="item.proname"
              :thumb="item.img1"
              :thumb-link="`/#/details/${item.proid}`"
            >
              <!-- <template #left> left </template> -->
              <template #num>
                <van-stepper
                  v-model="item.num"
                  theme="round"
                  :name="item.cartid"
                  button-size="22"
                  disable-input
                  @change="handleChangeGoodNum"
                />
              </template>
            </van-card>
          </div>
          <template #right>
            <van-button
              square
              text="删除"
              @click="handleDeleteGood(item.cartid)"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
      </van-pull-refresh>

      <van-divider>可能你还想要</van-divider>

      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="getRecommendlist"
      >
        <GoodsList ref="goodList" :goodsList="recommendList" />
      </van-list>
      <van-submit-bar :price="totalPrice" button-text="去结算" @submit="onSubmit">
        <van-checkbox @click="handleSelectAll" v-model="checked"> 全选 </van-checkbox>
        <!-- <template #tip>
          你的收货地址不支持同城送,
          <span @click="onClickEditAddress">修改地址</span>
        </template> -->
      </van-submit-bar>
    </div>
  </div>
</template>

<script lang="ts" setup>
/**
 * 全选功能实现思路：
 * 1. 商品列表的item-list添加van-checkbox，绑定的值为item.flag
 * 2. 每个check-box绑定click事件用于发送单个选中状态change的请求给后端（如果使用change，全选按钮值变化导致单个checkbox改变的时候也会触发）
 * 3. 全选checkbox的绑定一个computed属性：get返回cartlist的every（判断flag是否全部为true），所以单个checkbox发生变化也会影响这个computed属性，set：遍历cartlist，每个item的flag变为true
 * 4. 全选checkbox绑定一个click事件，用于向后端发送changeall的请求
 */

import GoodsList from '@/components/GoodsList.vue'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { cartUpdateSelectall } from '@/api/cart'
import { useCartList, useRecommendList } from '@/hooks/cartHook'
const user = useUserStore()
const cartStore = useCartStore()
const router = useRouter()

console.log
type CartItem = {
  proid: string
  num: number
  flag: boolean
  originprice: number
  proname: string
  img1: string
  cartid: string
}

const {
  cartList,
  isLoading,
  handleChangeGoodNum,
  handleDeleteGood,
  handleSelectOne,
  refresh,
} = useCartList(user, cartStore)

const { loading, finished, recommendList, getRecommendlist } = useRecommendList()

// header
const onClickLeft = () => {
  router.go(-1)
}
const totalNum = computed(() => {
  return cartStore.cartList
    ?.filter((item: CartItem) => item.flag)
    .reduce((curren: number, next: CartItem) => {
      return curren + next.num
    }, 0)
})

// footer
const totalPrice = computed(() => {
  return (
    cartList.value
      ?.filter((item: CartItem) => item.flag)
      .reduce((curren: number, next: CartItem) => {
        return curren + next.originprice * next.num
      }, 0) * 100
  )
})

const onSubmit = () => {
  // 提交订单要做什么：1. 跳转到订单页面, 2. 已选中信息保存到本地（sessionStorage）
  // 订单页面展示什么：2. 商品信息
  sessionStorage.setItem(
    'selectedCartList',
    JSON.stringify(cartList.value.filter((item: CartItem) => item.flag))
  )
  router.push('/order')
}

const checked = computed({
  get() {
    return cartList.value?.every((item: CartItem) => item.flag)
  },
  set(val) {
    console.log(val)
    cartList.value?.forEach((element: CartItem) => {
      element.flag = val
    })
  },
})

const handleSelectAll = () => {
  cartUpdateSelectall({
    userid: user.userid,
    type: checked.value,
  })
    .then((res) => {
      console.log('checkall', res)
    })
    .catch((err) => console.error(err))
}
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: yellowgreen;

  .list-container {
    flex: 1;
    .van-swipe-cell {
      .cell-left {
        display: flex;
        .van-checkbox {
          width: 80px;
          box-sizing: border-box;
          padding-left: 25px;
        }
        .van-card {
          flex: 1;
        }
      }
    }
  }
  .goods-card {
    margin: 0;
    background-color: #fff;
  }

  .delete-button {
    height: 100%;
  }
}
</style>
